/*
 * Copyright 2008 Wink Saville
 * 
 * This program is free software: you can redistribute it and/or modify
 * it under the terms of the GNU Lesser General Public License version 3
 * as published by the Free Software Foundation.
 *
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU Lesser General Public License for more details.
 *
 * You should have received a copy of the GNU Lesser General Public License
 * along with this program.  If not, see <http://www.gnu.org/licenses/>.
 */
package com.saville.serdes;

import java.util.concurrent.atomic.*;


public class StringSer implements ISerdes<String> {
    public static final int SERDES_ID = 1;
    public static final String SERDES_ID_STRING = "1";

    public String strg;

    public StringSer() {
        strg = null;
    }

    public StringSer(String s) {
        strg = s;
    }

    public int serdesId() {
        return SERDES_ID;
    }

    public String serdesIdString() {
        return SERDES_ID_STRING;
    }

    public ISerdes<String> make() {
        return new StringSer();
    }

    public void serialize(SerdesBinary serdesBinary) {
        serdesBinary.writeInt(serdesId());
        serdesBinary.writeString(strg);
    }

    public String deserialize(SerdesBinary serdesBinary) {
        strg = serdesBinary.readString();
        return strg;
    }
    
    public void serialize(SerdesJson serdesJson) {
        try {
            serdesJson.startObject();
            serdesJson.writeKey(serdesIdString());
            serdesJson.writeString(strg);
            serdesJson.endObject();
        } catch (Exception e) {
            throw new RuntimeException("StringSer#serialize json error");
        }
    }

    public String deserialize(SerdesJson serdesJson) {
        try {
            strg = (String) serdesJson.jt.nextValue();
        } catch (Exception e) {
            throw new RuntimeException("StringSer#deserialize json error");
        }
        return strg;
    }
    
    /*
     * This code should be present in all classes
     * that implement ISerdes
     */
    {
        if (registered.compareAndSet(0, 1)) {
            SerdesBinary.register(serdesId(), this);
            SerdesJson.register(serdesId(), this);
        }
    }
    
    private static final AtomicInteger registered = new AtomicInteger();
}
